import json
import os
import time

def sim_forment_time_str(time_str: str):
    l = time_str.split('-')
    return "%04d-%02d-%02d" % (int(l[0]), int(l[1]), int(l[2]))


def chick_dictionary(a_weibo: dict):
    min_time_str = sim_forment_time_str(a_weibo['date'])
    min_time = int(min_time_str.replace('-', ''))
    for reply in a_weibo['reply']:
        reply_time_str = sim_forment_time_str(reply['date'])
        reply_time = int(reply_time_str.replace('-', ''))
        if reply_time < min_time:
            min_time = reply_time
            min_time_str = reply_time_str
    a_weibo['date'] = min_time_str
    return a_weibo

def show_time(start_t, p):
    now_t = time.time()
    t = now_t - start_t
    ana = (t / p) * (1 - p)
    print("已用时 %.2f 秒(%.1f 分钟)" % (t, t / 60), end='')
    print("预计剩余 %.2f 秒(%.1f 分钟)，\n预计完成时间 %s." % (ana, ana / 60, time.asctime(time.localtime(now_t + ana))))

def form_time(time_str: str):
    l = time_str.split('-')
    return "%04d-%02d-%02d" % (int(l[0]), int(l[1]), int(l[2]))


def main_run(json_file_path:str, out_put_dir:str, moudle_name:str):

    #注意：这是修改后的内容#在此注释中间的内容谨慎修改！2020年7月27日16:37:55##################################################
    #out_put_dir = ""
    print(json_file_path)
    """if is_auto_path_name is False:
        print(out_put_dir)#" = input("请输入输出文件夹").replace('"', '')"
    else:
        out_put_dir = "json_to_txt_out_put/json_to_txt_%d" % time.time()"""
    """if os.path.exists(out_put_dir):
        print("已经存在了，取消")
        return"""
    """else:
        print(out_put_dir + " 是合法的路径.")"""
    out_put_dir=os.path.join(out_put_dir, moudle_name)# 注意！在这里面加了模块名！
    print("将在\n    %s\n 目录内进行操作,是否继续？[y/n]"%out_put_dir)
    c = input()
    if (c != 'y') and (c!= 'Y'):
        return
    os.makedirs(out_put_dir)

    os.makedirs(os.path.join(out_put_dir, "reply"))
    print("已建立文件夹")
    reply_out_put_dir = os.path.join(out_put_dir, "reply")
    # 注意：这是修改后的内容#在此注释中间的内容谨慎修改！2020年7月27日16:37:55#################################################


    myobj = json.load(open(json_file_path, 'r', encoding='utf-8'))
    myobj.remove(myobj[-1])
    start_t = time.time()#开始
    all_num = len(myobj)#总长度
    index = 1
    reply_index = 1

    f_index_txt = open(os.path.join(out_put_dir, "index.txt"), 'w+', encoding='utf-8')
    for weiboDirectory in myobj:
        weiboDirectory=chick_dictionary(weiboDirectory)
        mytime = form_time(weiboDirectory["date"])
        weiboDirectory_name="%s_%03d_%04d" % (mytime, index, weiboDirectory['reply_num'])

        f_index_txt.write("%s.txt\n" % weiboDirectory_name)# 向索引写入一条记录！
        with open(os.path.join(out_put_dir,"%s.txt" % weiboDirectory_name), "w+", encoding="utf-8") as f:
            f.write("%s\t%s\t%d\t%s" % (
                mytime,
                weiboDirectory["username"],
                weiboDirectory["reply_num"],
                weiboDirectory["text"]
            ))
        os.makedirs(
            os.path.join(reply_out_put_dir, weiboDirectory_name)
        )
        reply_index=1
        # 遍历回复！
        reply_index_txt = open(
            os.path.join(
                reply_out_put_dir,
                weiboDirectory_name,
                "reply_index.txt"
                ),
            'w+',
            encoding='utf-8'
        )
        for reply_obj in weiboDirectory["reply"]:
            reply_time=form_time(reply_obj["date"])
            reply_index_txt.write("%s_%03d.txt\n" % (reply_time, reply_index))
            with open(
                    os.path.join(
                        reply_out_put_dir,
                        weiboDirectory_name,
                        "%s_%03d.txt" % (reply_time, reply_index)
                    ).replace('/', '\\'), "w+", encoding="utf-8"
            ) as f:
                f.write("%s\t%s\t%d\t%s" % (
                    reply_time,
                    reply_obj["username"],
                    reply_obj["reply_num"],
                    reply_obj["text"]
                ))
                reply_index+=1
        reply_index_txt.close()
        if index%7==0:
            print("已完成%.2f%%"%((index/all_num)*100))
            show_time(start_t=start_t, p=(index/all_num))
        index += 1
    f_index_txt.close()
    print("Done.")

def main():
    if os.path.isfile("tjtt.ini") is False:
        while True:
            json_file_path = input("请输入 json 文件名:\n > ").replace('"', '')
            if os.path.isfile(json_file_path) is False:
                print("错误的路径！")
                continue
            else:
                print("正确的路径！")
                break

        while True:
            out_put_dir_path = input("请输入 输出文件夹 路径:\n > ").replace('"', '')
            if (os.path.exists(out_put_dir_path) is False) or (os.path.isfile(out_put_dir_path) is True):
                print("错误的路径！")
                continue
            else:
                print("正确的路径！")
                break
        moudle_name = json_file_path.split('\\')[-1].split('/')[-1].replace('.json', '')
    else:
        print("配置文件暂未开发.请手动输入路径.")
        return

    main_run(json_file_path=json_file_path, out_put_dir=out_put_dir_path, moudle_name=moudle_name)

main()
